package com.cskaoyan.javase.oop1._8callby;

/**
 * 值传递练习
 * 使用类创建对象,证明Java只有值传递
 *
 * @since 17:23
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    public static void main(String[] args) {
        Student s = new Student(18);
        /*
            Java是值传递,虽然方法接收的是引用的拷贝,但终究指向同一个对象
            所以Java的方法可以修改对象中成员变量的取值,称之为改变对象的状态
         */
        doubleStuAge(s);
        System.out.println(s.age);
        System.out.println("---------------------");

        Student s1 = new Student(18);
        Student s2 = new Student(81);
        System.out.println("交换之前s1:" + s1.age);
        System.out.println("交换之前s2:" + s2.age);
        /*
            方法得到的只是引用的拷贝,所以交换是不可能成功的!
            Java是值传递的!
         */
        swapStuReference(s1, s2);
        System.out.println("交换之后s1:" + s1.age);
        System.out.println("交换之后s2:" + s2.age);
    }

    public static void doubleStuAge(Student s) {
        s.age *= 2;
    }

    public static void swapStuReference(Student s1, Student s2) {
        Student temp = s1;
        s1 = s2;
        s2 = temp;
        System.out.println("交换方法之中s1:" + s1.age);
        System.out.println("交换方法之中s2:" + s2.age);
    }

}

class Student {
    int age;

    public Student() {
    }

    public Student(int age) {
        this.age = age;
    }
}